﻿using System;
using System.IO;
using System.Collections.Generic;

namespace EpubTools
{
	class XmlTools
	{
		/// <summary>
		/// "Convert" the specified XML 1.1 file to an XML 1.0 file at the specified path
		/// by updating the XML header. (This does no validation or conversion of other
		/// XML 1.0-invalid semantics.)
		/// </summary>
		/// <param name="xml11path">Path to the XML 1.1 file.</param>
		/// <param name="xml10path">Path to the XML 1.0 file.</param>
		public static void convertXml11toXml10(string xml11path, string xml10path)
		{
			// Open the file, and prep our list that will be used to build output.
			StreamReader inputXml = new StreamReader(xml11path);
			List<String> outputXmlBuilder = new List<String>();

			// Check to see if this is a valid file. If it is, load it into the list. If not, bail.
			bool validInput = true;
			try
			{
				string lineInput = inputXml.ReadLine();
				if (lineInput.Trim().Substring(0, 19) != "<?xml version=\"1.1\"")
				{
					validInput = false;
				}

				// Need to assemble the XML file in memory, in case input/output files are the same.
				outputXmlBuilder.Add("<?xml version=\"1.0\"" + lineInput.TrimStart().Substring(19));
				while ((lineInput = inputXml.ReadLine()) != null)
				{
					outputXmlBuilder.Add(lineInput);
				}
			}
			finally
			{
				inputXml.Close();
			}
			if (!validInput)
			{
				throw new ArgumentException("Input XML file is not a recognized XML 1.1 file", "xml11path");
			}

			// Write the updated file.
			StreamWriter outputXml = new StreamWriter(xml10path);
			foreach (string lineOutput in outputXmlBuilder)
			{
				outputXml.WriteLine(lineOutput);
			}
			outputXml.Close();
		}

/*		public static bool tryConvertXml11toXml10(string xml11path, string xml10path)
		{
			bool result = true;

			try
			{
				convertXml11toXml10(xml11path, xml10path);
			}
			catch (ArgumentException e)
			{
				if (e.ParamName != "xml11path")
				{
					// This isn't a "known exception", so rethrow it.
					throw;
				}
				result = false;
			}

			return result;
		}*/
	}
}
